// 从 pinia 模块中导入 defineStore 函数
import { defineStore } from 'pinia'

// 添加首页标签
function addHomeTag(tagsViewList) {
  tagsViewList.unshift({
    fullPath: '/dashboard',
    meta: { title: '首页', affix: true, icon: 'dashboard' },
    name: 'DashboardIndex',
    params: {},
    path: '/dashboard',
    query: {},
    title: '首页'
  })
}

// 检查是否存在首页标签
function hasHomeTag(tagsViewList) {
  return tagsViewList.some((item) => {
    return item.fullPath === '/dashboard'
  })
}

// 定义并导出 useTagsViewStore，使用 defineStore 创建 store
export const useTagsViewStore = defineStore('tagsView', {
  state: () => {
    return {
      tagsViewList: []
    }
  },
  actions: {
    /**
     * 添加 tags
     */
    addTagsViewList(tag) {
      this.$patch((state) => {
        const isFind = state.tagsViewList.find((item) => {
          return item.path === tag.path
        })
        // 处理重复
        if (!isFind) {
          state.tagsViewList.push(tag)
        }
        if (!hasHomeTag(state.tagsViewList)) {
          addHomeTag(state.tagsViewList)
        }
      })
    },
    /**
     * 删除 tag
     * @param {type: 'other'||'right'||'index', index: index} payload
     */
    removeTagsView(payload, callback = () => {}) {
      this.$patch((state) => {
        if (payload.type === 'index') {
          state.tagsViewList.splice(payload.index, 1)
        } else if (payload.type === 'other') {
          state.tagsViewList.splice(
            payload.index + 1,
            state.tagsViewList.length - payload.index + 1
          )
          state.tagsViewList.splice(0, payload.index)
          if (payload.index != 0) {
            addHomeTag(state.tagsViewList)
          }
          callback(state.tagsViewList)
        } else if (payload.type === 'right') {
          state.tagsViewList.splice(
            payload.index + 1,
            state.tagsViewList.length - payload.index + 1
          )
          callback(state.tagsViewList)
        } else if (payload.type === 'all') {
          state.tagsViewList = [
            {
              fullPath: '/dashboard',
              meta: { title: '首页', affix: true, icon: 'dashboard' },
              name: 'DashboardIndex',
              params: {},
              path: '/dashboard',
              query: {},
              title: '首页'
            }
          ]
        }
      })
    },
    //删除所有tag
    removeAllTagsView() {
      this.$patch((state) => {
        state.tagsViewList = []
      })
    }
  },
  // 开启数据缓存
  // 配置持久化存储方式为localStorage
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['tagsViewList']
      }
    ]
  }
})
// 导出 useTagsViewStore
export default useTagsViewStore
